package redis

import (
	"time"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"server/bitkop/core/config"
)

type RedisPools struct {
	OTEPool 		*redis.Pool
}

func NewRedisPools(config map[string]config.RedisConfig) *RedisPools {
	return &RedisPools{
		OTEPool:		GetRedisPool(config["ote"]),
	}
}

// create new redis pool.
func GetRedisPool(cfg config.RedisConfig) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     30,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", cfg.GetHost(), cfg.GetPort()), redis.DialDatabase(cfg.GetDB()))
			if err != nil {
				return nil, err
			}
			if cfg.GetAuth() != "" {
				if _, err := c.Do("AUTH", cfg.GetAuth()); err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, err
		},

		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) < 5 * time.Second {
				return nil
			}
			_, err := c.Do("PING")
			return err
		},
	}
}